<template>
  <!--  商业险保司报价-->
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :inline="false" :label-position="labelPosition" :class="isEdit?'':'formItem'">
    <!--商业险信息-->
    <el-card class="box-card" shadow="never">

      <div slot="header" class="header-card">
        <span class="header-card-title">商业险信息</span>
      </div>

      <!--保司报价节点-->
      <el-row :gutter="24">

        <el-col :span="8">
          <el-form-item label="商业险公司:">
            <el-input v-model="ruleForm.syxCompany" disabled />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="商业险公司编码:">
            <el-input v-model="ruleForm.syxCompanyCode" disabled />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="商业险起保日:" prop="syxExpectBeginTime" v-if="isShow">
            <el-date-picker @change="changeData(ruleForm.syxExpectBeginTime)" v-model="ruleForm.syxExpectBeginTime" type="date" placeholder="请选择商业险起保日" v-if="isEdit" value-format='yyyy-MM-dd' style="width: 100%;">
            </el-date-picker>
            <span v-else>{{ ruleForm.syxExpectBeginTime }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="商业险到期日:" prop="syxExpectEndTime" v-if="isShow">
            <el-date-picker v-model="ruleForm.syxExpectEndTime" type="date" placeholder="请选择商业险到期日" v-if="isEdit" value-format='yyyy-MM-dd' style="width: 100%;">
            </el-date-picker>
            <span v-else>{{ ruleForm.syxExpectEndTime }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="商业险性质:" prop="syxInsuranceType" v-if="isShow">
            <el-select v-model="ruleForm.syxInsuranceType" disabled style="width: 100%;" placeholder="请选择商业险性质">
              <el-option label="运营" value="1">
              </el-option>
              <el-option label="非运营" value="2">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

<!--        <el-col :span="8">-->
<!--          <el-form-item label="商业险保费:" prop="syxAmount" v-if="isShow">-->
<!--            <el-input v-model="ruleForm.syxAmount" disabled v-if="isEdit" @change="changeAmount('syxAmount')" placeholder="商业险保费"></el-input>-->
<!--            <span v-else>{{ format_thousand(ruleForm.syxAmount) }}</span>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
      </el-row>

      <!--保险套餐-->
      <el-row :gutter="24">
        <el-col :span="24">
          <div style="padding-bottom:8px;font-size: 16px;">保险套餐</div>
          <el-table :data="ruleForm.businessList" border size='mini'>
            <el-table-column align="center" prop="insuranceProName" label="商业险种" />

            <el-table-column align="center" prop="insuranceQuota" label="保额/万元" >
              <template #default="{row}">
                <span v-if="typeof row.insuranceQuota === 'number'">
                  {{format_thousand( row.insuranceQuota) || '--' }}
                </span>
                <span>
                  {{row.insuranceQuota}}
                </span>
              </template>
            </el-table-column>

            <el-table-column align="center" label="保险费用/元">
              <template #default="{row,$index}">
                <el-form-item class="formTable">
                  <el-input v-if="isEdit" v-model="row.insurancePrice"  v-thousand
                  @change="changeTable(row, $index, 'insurancePrice')" size="mini" />
                  <span v-else>{{ format_thousand(row.insurancePrice) }}</span>
                </el-form-item>

              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>
  </el-form>
</template>

<script>
import { effectDate } from "@/utils/libs/effectDate.js"

export default {
  name: 'syxWarrantyOffer',//商业险保司报价
  dicts: ["insurance_channels", "insurance_project"],
  props: {
    value: {
      type: Object,
      default: {},
    },
    state: {
      type: String,
      default: "",
    },
    activityId: {
      type: String,
      default: "",
    },
    pageConfig: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  components: {
    insuranceSelect: () => import('../insuranceSelect')
  },
  computed: {
    ruleForm: {
      get() {
        let that = this;
        const proxy = new Proxy(that.value, {
          get(target, key) {
            return Reflect.get(target, key);
          },
          set(target, key, value) {
            if (value) {
              that.handleClearValidate(key)
            }
            that.handleData(key, value)
            that.$emit("input", { ...target, [key]: value });
            return true;
          },
        });
        return proxy;
      },
    },
    labelPosition() {
      if (this.state === 'write') {
        return 'top'
      } else {
        return 'right'
      }
    },
    isEdit() {
      let bool;
      switch (this.state) {
        case "write":
          bool = true;
          break;
        case "disabled":
          bool = false;
          break;
        case "readonly":
          bool = false;
          break;
      }
      return bool
    }
  },
  watch:{
    'value.businessList':{
      handler(val) {
        if (val) {

        }
      },
      immediate: true,
      deep: true
    }
  },
  data() {
    var start = (rule, value, callback) => {
      let that = this
      effectDate(rule, value, callback,
        that.ruleForm.syxExpectBeginTime,
        that.ruleForm.syxExpectEndTime,
        '商业险起保日',
        '商业险到期日'
      )
    };
    var end = (rule, value, callback) => {
      let that = this
      effectDate(rule, value, callback,
        that.ruleForm.syxExpectBeginTime,
        that.ruleForm.syxExpectEndTime,
        '商业险起保日',
        '商业险到期日'
      )
    };
    return {
      isShow: true,
      rules: {
        //商业险信息
        syxCompany: [
          { required: this.state === 'write', message: "请选择商业险公司", trigger: "blur" },
        ],
        syxPolicyCode: [
          { required: this.state === 'write', message: "请输入商业险保单号", trigger: "blur" },
        ],
        syxCompanyCode: [
          { required: this.state === 'write', message: "请输入商业险公司编码", trigger: "blur" },
        ],
        syxExpectBeginTime: [
          { required: this.state === 'write', validator: start, trigger: "blur" },
        ],
        syxExpectEndTime: [
          { required: this.state === 'write', validator: end, trigger: "blur" },
        ],
        syxInsuranceType: [
          { required: this.state === 'write', message: "请选择商业险性质", trigger: "blur" },
        ],
        syxAmount: [
          { required: this.state === 'write', message: "请输入商业险保费", trigger: "blur" },
        ],
        syxPolicyUrl: [
          { required: this.state === 'write', message: "请输入商业险保单", trigger: "blur" },
        ]
      },
    };
  },
  created() {
    this.handlePrice()
  },
  mounted() {
    this.$nextTick(() => {
      this.ruleForm?.syxExpectBeginTime && this.changeData(this.ruleForm?.syxExpectBeginTime)
    })
  },
  methods: {
    changeData(time) {
      let timeDate = this.addOneMonth(time, 12)
      this.$set(this.ruleForm, 'syxExpectEndTime', timeDate)
    },
    addOneMonth(dateString, month) {
      const date = new Date(dateString);
      date.setMonth(date.getMonth() + Number(month));
      date.setDate(date.getDate()-1)
      return date.toISOString().split('T')[0]; // 返回YYYY-MM-DD格式的日期字符串
    },
    handleShopInsurace() {
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            resolve();
          } else {
            reject();
          }
        });
      });
    },
    // 店保金额格式
    changeTable(row, key, field) {
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/;
      let _value
      if (!row[field]) return
      if (msg.test(Number(row[field]))) {
        if (Number(row[field]) >= 0) {
          _value = row[field].toString().match(/^\d+(?:\.\d{0,2})?/)[0];
          row[field] = _value;
        } else {
          row[field] = "";
        }
      } else {
        row[field] = "";
      }
      let key_ = this.dict.type.insurance_project.map(a => {
        if (Number(row.insuranceProCode) === Number(a.value)) {
          return a.raw.remark
        }
      }).filter(a => a)[0]

      for (let i = 0; i < this.value.insuranceVoList.length; i++) {
        if(key_){
          this.$set(this.value.insuranceVoList[i], key_, _value)
        }
      }
      this.handlePrice()
    },
    handlePrice() {
      let num = 0
      for (let i = 0; i < this.ruleForm.businessList.length; i++) {
        num += Number(this.ruleForm.businessList[i].insurancePrice)
      }
      this.$set(this.value,'syxAmount',num)
    },
    changeAmount(str) {
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/;
      if (!msg.test(this.ruleForm[str])) {
        this.ruleForm[str] = "";
      } else {
        this.ruleForm[str] = this.ruleForm[str]
          .toString()
          .match(/^\d+(?:\.\d{0,2})?/)[0];
      }
    },

    handleChange(val) {
      this.value.syxCompanyCode = val.code
      this.value.syxCompany = val.name
      this.value.syxCompanyId = val.id
      this.$refs.ruleForm.clearValidate('syxCompany')
      this.$refs.ruleForm.clearValidate('syxCompanyCode')
    },


    //取消表单效验
    handleClearValidate(str) {
      this.$refs.ruleForm.clearValidate(str);
    },
    valid() {
      return new Promise((resolve) => {
        this.$refs.ruleForm.validate((valid) => {
          resolve(valid);
        });
      });
    },

    handleData(key, value) {
      this.value.insuranceVoList.forEach(item => {
        item[key] = value
      })
    }
  },
};
</script>
<style scoped lang="scss">
@import "@/styles/cwgd/formScss.scss";
</style>

